// pages/park-ticket/components/buy-ticket/buyTicket.js
let request = require('../../../../utils/request.js')

Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    parkTicketList: [],
    selectedParkTicket: {},
    quantity: 1,
    amount: 0,
    btnLoading: false
  },
  ready() {
    //  获取平台停车券列表
    this.getBizParkTicket()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取平台停车券列表
     */
    getBizParkTicket(){
      request.http(
        '/business/park-ticket/all-ticket', 'GET'
      ).then(res => {
        let parkTicketList = res.data.data
        parkTicketList.forEach((parkTicket)=> {
          parkTicket.ticketName = parkTicket.parkingDuration + '小时券' + parkTicket.sellPrice + '元'
        })
        this.setData({
          parkTicketList: parkTicketList
        })
      })
    },
    /**
     * 加数量
     */
    addQuantity(){
      let quantity = this.data.quantity
      let selectedParkTicket = this.data.selectedParkTicket
      if(!selectedParkTicket.sellPrice){
        wx.showToast({ title: '请先选择则停车券', icon: 'none' })
        return
      }
      this.setData({
        quantity: ++quantity,
        amount: selectedParkTicket.sellPrice * quantity
      })
    },
    /**
     * 减数量
     */
    subQuantity(){
      let quantity = this.data.quantity
      let selectedParkTicket = this.data.selectedParkTicket
      //  最小为1
      if(quantity == 1) { return }
      if(!selectedParkTicket.sellPrice){
        wx.showToast({ title: '请先选择则停车券', icon: 'none' })
        return
      }

      this.setData({
        quantity: --quantity,
        amount: selectedParkTicket.sellPrice * quantity
      })
    },
    /**
     * 选择停车券
     */
    selectParkTicket(e){
      let parkTicket = e.target.dataset.item
      this.setData({
        selectedParkTicket: parkTicket,
        amount: parkTicket.sellPrice,
        quantity: 1,
      })
    },
    /**
     * 提交
     */
    submit(){
      if(!this.data.selectedParkTicket.id){
        wx.showToast({ title: '请选择停车券', icon: 'none' })
        return
      }

      let _this = this
      wx.login({
        success(loginRes) {
          //  获取openId
          request.http(
            '/shop/shop-info/get-open-id', 'GET', {code: loginRes.code}
          ).then(getOpenIdRes => {
            if (getOpenIdRes.data.code == 200) {
              _this.setData({ btnLoading: true })
              let params = {
                openId: getOpenIdRes.data.data.openId,
                bizParkTicketId: _this.data.selectedParkTicket.id,
                quantity: _this.data.quantity,
                paidAmount: _this.data.amount,
                originalAmount: _this.data.amount,
                shopId: wx.getStorageSync('shopId'),
                fromType: 1 //  来源 (1：商户购买；2：平台发放) 
              }
              //  下单
              request.http(
                '/shop/shop-park-ticket/buy-park-ticket', 'POST', params
              ).then(buyRes => {
                if (buyRes.data.code == 200) {
                  // 调起支付窗口
                  wx.requestPayment({
                    timeStamp: buyRes.data.data.timeStamp, // 时间戳，必填（后台传回）
                    nonceStr: buyRes.data.data.nonceStr, // 随机字符串，必填（后台传回）
                    package: buyRes.data.data.package, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
                    signType: 'MD5', // 签名算法，非必填，（预先约定或者后台传回）
                    paySign: buyRes.data.data.paySign, // 签名 ，必填 （后台传回）
                    success: (buyCallbackRes)=> { // 成功后的回调函数
                      wx.showToast({ title: '购买成功' })
                      _this.setData({ btnLoading: false })
                      _this.triggerEvent('closeDialog')

                      wx.redirectTo({  url: '/pages/mine/mine?activityTab=2' })
                    },
                    fail(err) { _this.setData({ btnLoading: false }) }
                  })
                } else { _this.setData({ btnLoading: false }) }
              })
            }
          })
        }
      })
    }
  }
})
